package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.*;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyLiJiuTong;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeLiJiuTong;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformMultiPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMaskConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 利久通 采 安心分期 API全 掩码28
 * @ author 李源聪
 * @ date 2025年07月16日 14:17
 */
@ApiPlan(productId = "345", type = ApiPlanConvertType.PLAT_PHONE_MASK)
public class ApiPlatLiJiuTongiPhoneMaskConvert implements ApiPlatformPhoneMaskConvertHandler {

    private static final String KEY = "882cfba76a555d309b7b72fd7653e7fd";
    private static final String CHANNEL_CODE = "VGNSXFOPWY";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {

        ApiPlatDataExchangeLiJiuTong apiPlatDataExchange = new ApiPlatDataExchangeLiJiuTong();
        // 掩码手机号
        apiPlatDataExchange.setPhone(apiDataExchangeParameter.getPhoneMask());
        // 用户名
        apiPlatDataExchange.setRealName("浩安星");
        // 用户ip
        apiPlatDataExchange.setIp("127.0.0.1");
        // 城市代码
        apiPlatDataExchange.setCityCode(apiDataExchangeParameter.getAreaCode());
        // 城市
        apiPlatDataExchange.setWorkCity(apiDataExchangeParameter.getCity());
        // 年龄
        apiPlatDataExchange.setAge(apiDataExchangeParameter.getAge());
        // 	性别 1-男 2-女 默认1
        String sex = ChooseEq.create(apiDataExchangeParameter.getSex())
                .when("0", "1")
                .when("1", "2")
                .end("1");
        apiPlatDataExchange.setGender(sex);
        // 贷款金额(元)贷款金额 50000-200000元 默认50000
        String loanAmount = ChooseEq.create(apiDataExchangeParameter.getLoanAmount())
                .when("1", "30000")
                .when("2", "50000")
                .when("3", "100000")
                .when("4", "200000")
                .end("50000");
        apiPlatDataExchange.setAmount(loanAmount);
        // 信用情况 0-无逾期 1-有逾期 默认0
        String overdue = ChooseEq.create(apiDataExchangeParameter.getOverdue())
                .when("1", "0")
                .when("2", "1")
                .when("3", "0")
                .end("0");
        apiPlatDataExchange.setCredit(overdue);
        // 学历 1:大专以下 2:大专 3:本科 4:研究生 5:博士 默认2
        String educationAttainment = ChooseEq.create(apiDataExchangeParameter.getEducationAttainment())
                .when("1", "1")
                .when("2", "1")
                .when("3", "1")
                .when("4", "2")
                .when("5", "3")
                .when("6", "4")
                .end("2");
        apiPlatDataExchange.setEducation(educationAttainment);
        // 职业 1-上班族 2-公务员/事业单位 3-私营业主 4-个体户 5-其他 默认1
        String career = ChooseEq.create(apiDataExchangeParameter.getCareer())
                .when("1", "2")
                .when("2", "1")
                .when("3", "4")
                .when("4", "3")
                .when("5", "5")
                .end("1");
        apiPlatDataExchange.setProfessional(career);
        // 月收入 1:5000以下 2:5000-1万 3:1万-1.5万 4:1.5万-2万 5:2万以上 默认2
        String monthlySalary = ChooseEq.create(apiDataExchangeParameter.getMonthlySalary())
                .when("1", "1")
                .when("2", "2")
                .when("3", "3")
                .when("4", "4")
                .when("5", "5")
                .end("2");
        apiPlatDataExchange.setMonthIncome(monthlySalary);
        // 工资发放形式 1-银行代发 2-转账工资 3-现金发放 默认1
        String salaryPayMethod = ChooseEq.create(apiDataExchangeParameter.getSalaryPayMethod())
                .when("1", "1")
                .when("2", "3")
                .when("3", "2")
                .end("1");
        apiPlatDataExchange.setSalaryType(salaryPayMethod);
        // 社保 0-无社保 1-有社保 默认0
        String socialSecurity = ChooseEq.create(apiDataExchangeParameter.getSocialSecurity())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .end("0");
        apiPlatDataExchange.setSocialSecurity(socialSecurity);
        // 公积金（ 0-无； 1-.未满6个月 ；2-6个月及以上）
        String providentFund = ChooseEq.create(apiDataExchangeParameter.getProvidentFund())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "1")
                .end("0");
        apiPlatDataExchange.setAccumulationFund(providentFund);
        // 房产情况 0-无房 1-有 默认0
        String realEstateInfo = ChooseEq.create(apiDataExchangeParameter.getRealEstateInfo())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .when("5", "1")
                .when("6", "1")
                .end("0");
        apiPlatDataExchange.setHouse(realEstateInfo);
        // 车产情况 0-无车 1-有 默认0
        String carInfo = ChooseEq.create(apiDataExchangeParameter.getCarInfo())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .end("0");
        apiPlatDataExchange.setVehicle(carInfo);
        // 保单 0-无保单 1-有保单 默认0
        String insurancePolicy = ChooseEq.create(apiDataExchangeParameter.getInsurancePolicy())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "1")
                .end("0");
        apiPlatDataExchange.setInsurance(insurancePolicy);
        // 信用卡 0:无信用卡 1:1-5万 2:5-10万 3:10-20万 4:20万以上 默认0
        String creditLimit = ChooseEq.create(apiDataExchangeParameter.getCreditLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .when("5", "1")
                .when("6", "1")
                .end("0");
        apiPlatDataExchange.setCreditCard(creditLimit);
        // 芝麻分 0:无芝麻分 1:600分以下 2:600-650分 3:650-700分 4:700分以上 默认1
        String sesameCredit = ChooseEq.create(apiDataExchangeParameter.getSesameCredit())
                .when("1", "1")
                .when("2", "2")
                .when("3", "3")
                .when("4", "4")
                .end("1");
        apiPlatDataExchange.setSesameScore(sesameCredit);
        // 花呗 0:无花呗 1:1-5万 2:5-10万 3:10-20万 4:20万以上 默认0
        String hbLimit = ChooseEq.create(apiDataExchangeParameter.getHbLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .when("5", "1")
                .end("0");
        apiPlatDataExchange.setHuabei(hbLimit);
        // 京东白条京东白条 0:无白条 1:1-5万 2:5-10万 3:10-20万 4:20万以上 默认0
        String btLimit = ChooseEq.create(apiDataExchangeParameter.getBtLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .when("5", "1")
                .end("0");
        apiPlatDataExchange.setBaitiao(btLimit);
        // 借款期限 1:1-3个月 2:3-6个月 3:6-12个月 4:1-2年 5:2年以上 默认3
        String termNum = ChooseEq.create(apiDataExchangeParameter.getLoanTerm())
                .when("1", "1")
                .when("2", "2")
                .when("3", "3")
                .when("4", "4")
                .when("5", "5")
                .when("6", "6")
                .end("3");
        apiPlatDataExchange.setLoanTerm(termNum);
        // 借款用途 1-购房 2-购车 3-住房装修 4-教育深造 5-休闲旅游 6-个人消费 7-房租缴纳 8-其他贷款 默认6
        String loanPurpose = ChooseEq.create(apiDataExchangeParameter.getLoanPurpose())
                .when("1", "5")
                .when("2", "4")
                .when("3", "8")
                .when("4", "3")
                .when("5", "8")
                .when("6", "6")
                .end("6");
        apiPlatDataExchange.setLoanUse(loanPurpose);
        // 用户设备 1-Android 2-IOS 默认1
        apiPlatDataExchange.setClient("1");
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(apiPlatDataExchange));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("content", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformMultiPhoneMaskDataExchange respDataExchange(String respJson) throws Exception {
        //  撞库返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }

        JSONObject resData = jsonObject.getJSONObject("data");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }

        RespPlatformMultiPhoneMaskDataExchange respPlatformMultiPhoneMaskDataExchange = RespPlatformMultiPhoneMaskDataExchange.ofSuc();
        List<RespPlatformPhoneMaskDataExchange> listRespPlatformPhoneMaskDataExchange = CollUtils.newArrayList();
        if (ValidParam.isNotNull(resData)) {
            BigDecimal price = resData.getBigDecimal("originalPrice");
            String companyName = resData.getString("companyName");
            String productName = resData.getString("productName");
            String logo = resData.getString("logo");
            String orderId = resData.getString("orderNum");

            List<ApiProtocol> protocolList = CollUtils.newArrayList(newList -> {
                //  获取协议
                JSONArray listProtocolResult = resData.getJSONArray("protocolList");
                IteratorUtils.array(listProtocolResult, (protocolResult, index) -> {
                    JSONObject protocolObject = listProtocolResult.getJSONObject(index);
                    ApiProtocol protocol = new ApiProtocol();
                    protocol.setProtocolName(protocolObject.getString("protocolName"));
                    protocol.setProtocolUrl(protocolObject.getString("protocolUrl"));
                    newList.add(protocol);
                });
            });

            List<String> phoneMd5List = CollUtils.newArrayList(newList -> {
                JSONArray jsonArray = resData.getJSONArray("md5List");
                IteratorUtils.array(jsonArray, (protocolResult, index) -> {
                    String phoneMd5 = jsonArray.getString(index);
                    newList.add(phoneMd5);
                });
            });

            RespPlatformPhoneMaskDataExchange result = RespPlatformPhoneMaskDataExchange.of();
            result.setPrice(price);
            result.setLogoPath(logo);
            result.setDisplayName(companyName);
            result.setProductName(productName);
            result.setApplyId(orderId);
            result.setProtocolList(protocolList);
            result.setListPhoneMd5(phoneMd5List);
            listRespPlatformPhoneMaskDataExchange.add(result);
        }
        respPlatformMultiPhoneMaskDataExchange.setListPhoneMask(listRespPlatformPhoneMaskDataExchange);
        return respPlatformMultiPhoneMaskDataExchange;
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {

        ApiPlatApplyLiJiuTong apiPlatApplyLiJiuTong = new ApiPlatApplyLiJiuTong();
        apiPlatApplyLiJiuTong.setOrderNum(apiApplyParameter.getApplyId());
        // 掩码手机号
        apiPlatApplyLiJiuTong.setPhone(apiApplyParameter.getPhone());
        // 用户名
        apiPlatApplyLiJiuTong.setRealName(apiApplyParameter.getUserName());
        // 用户ip
        apiPlatApplyLiJiuTong.setIp("127.0.0.1");
        // 城市代码
        apiPlatApplyLiJiuTong.setCityCode(apiApplyParameter.getAreaCode());
        // 城市
        apiPlatApplyLiJiuTong.setWorkCity(apiApplyParameter.getCity());
        // 年龄
        apiPlatApplyLiJiuTong.setAge(apiApplyParameter.getAge());
        // 性别（0-女;1-男（默认））
        String sex = ChooseEq.create(apiApplyParameter.getSex())
                .when("0", "1")
                .when("1", "2")
                .end("1");
        apiPlatApplyLiJiuTong.setGender(sex);
        // 贷款金额(元)贷款金额 50000-200000元 默认50000
        String loanAmount = ChooseEq.create(apiApplyParameter.getLoanAmount())
                .when("1", "30000")
                .when("2", "50000")
                .when("3", "100000")
                .when("4", "200000")
                .end("50000");
        apiPlatApplyLiJiuTong.setAmount(loanAmount);
        // 信用情况 0-无逾期 1-有逾期 默认0
        String overdue = ChooseEq.create(apiApplyParameter.getOverdue())
                .when("1", "0")
                .when("2", "1")
                .when("3", "0")
                .end("0");
        apiPlatApplyLiJiuTong.setCredit(overdue);
        // 学历 1:大专以下 2:大专 3:本科 4:研究生 5:博士 默认2
        String educationAttainment = ChooseEq.create(apiApplyParameter.getEducationAttainment())
                .when("1", "1")
                .when("2", "1")
                .when("3", "1")
                .when("4", "2")
                .when("5", "3")
                .when("6", "4")
                .end("2");
        apiPlatApplyLiJiuTong.setEducation(educationAttainment);
        // 职业 1-上班族 2-公务员/事业单位 3-私营业主 4-个体户 5-其他 默认1
        String career = ChooseEq.create(apiApplyParameter.getCareer())
                .when("1", "2")
                .when("2", "1")
                .when("3", "4")
                .when("4", "3")
                .when("5", "5")
                .end("1");
        apiPlatApplyLiJiuTong.setProfessional(career);
        // 月收入 1:5000以下 2:5000-1万 3:1万-1.5万 4:1.5万-2万 5:2万以上 默认2
        String monthlySalary = ChooseEq.create(apiApplyParameter.getMonthlySalary())
                .when("1", "1")
                .when("2", "2")
                .when("3", "3")
                .when("4", "4")
                .when("5", "5")
                .end("2");
        apiPlatApplyLiJiuTong.setMonthIncome(monthlySalary);
        // 工资发放形式 1-银行代发 2-转账工资 3-现金发放 默认1
        String salaryPayMethod = ChooseEq.create(apiApplyParameter.getSalaryPayMethod())
                .when("1", "1")
                .when("2", "3")
                .when("3", "2")
                .end("1");
        apiPlatApplyLiJiuTong.setSalaryType(salaryPayMethod);
        // 社保 0-无社保 1-有社保 默认0
        String socialSecurity = ChooseEq.create(apiApplyParameter.getSocialSecurity())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .end("0");
        apiPlatApplyLiJiuTong.setSocialSecurity(socialSecurity);
        // 公积金（ 0-无； 1-.未满6个月 ；2-6个月及以上）
        String providentFund = ChooseEq.create(apiApplyParameter.getProvidentFund())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "1")
                .end("0");
        apiPlatApplyLiJiuTong.setAccumulationFund(providentFund);
        // 房产情况 0-无房 1-有 默认0
        String realEstateInfo = ChooseEq.create(apiApplyParameter.getRealEstateInfo())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .when("5", "1")
                .when("6", "1")
                .end("0");
        apiPlatApplyLiJiuTong.setHouse(realEstateInfo);
        // 车产情况 0-无车 1-有 默认0
        String carInfo = ChooseEq.create(apiApplyParameter.getCarInfo())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .end("0");
        apiPlatApplyLiJiuTong.setVehicle(carInfo);
        // 保单 0-无保单 1-有保单 默认0
        String insurancePolicy = ChooseEq.create(apiApplyParameter.getInsurancePolicy())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "1")
                .end("0");
        apiPlatApplyLiJiuTong.setInsurance(insurancePolicy);
        // 信用卡 0:无信用卡 1:1-5万 2:5-10万 3:10-20万 4:20万以上 默认0
        String creditLimit = ChooseEq.create(apiApplyParameter.getCreditLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .when("5", "1")
                .when("6", "1")
                .end("0");
        apiPlatApplyLiJiuTong.setCreditCard(creditLimit);
        // 芝麻分 0:无芝麻分 1:600分以下 2:600-650分 3:650-700分 4:700分以上 默认1
        String sesameCredit = ChooseEq.create(apiApplyParameter.getSesameCredit())
                .when("1", "1")
                .when("2", "2")
                .when("3", "3")
                .when("4", "4")
                .end("1");
        apiPlatApplyLiJiuTong.setSesameScore(sesameCredit);
        // 花呗 0:无花呗 1:1-5万 2:5-10万 3:10-20万 4:20万以上 默认0
        String hbLimit = ChooseEq.create(apiApplyParameter.getHbLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .when("5", "1")
                .end("0");
        apiPlatApplyLiJiuTong.setHuabei(hbLimit);
        // 京东白条京东白条 0:无白条 1:1-5万 2:5-10万 3:10-20万 4:20万以上 默认0
        String btLimit = ChooseEq.create(apiApplyParameter.getBtLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .when("5", "1")
                .end("0");
        apiPlatApplyLiJiuTong.setBaitiao(btLimit);
        // 借款期限 1:1-3个月 2:3-6个月 3:6-12个月 4:1-2年 5:2年以上 默认3
        String termNum = ChooseEq.create(apiApplyParameter.getLoanTerm())
                .when("1", "1")
                .when("2", "2")
                .when("3", "3")
                .when("4", "4")
                .when("5", "5")
                .when("6", "6")
                .end("3");
        apiPlatApplyLiJiuTong.setLoanTerm(termNum);
        // 借款用途 1-购房 2-购车 3-住房装修 4-教育深造 5-休闲旅游 6-个人消费 7-房租缴纳 8-其他贷款 默认6
        String loanPurpose = ChooseEq.create(apiApplyParameter.getLoanPurpose())
                .when("1", "5")
                .when("2", "4")
                .when("3", "8")
                .when("4", "3")
                .when("5", "8")
                .when("6", "6")
                .end("6");
        apiPlatApplyLiJiuTong.setLoanUse(loanPurpose);
        // 用户设备 1-Android 2-IOS 默认1
        apiPlatApplyLiJiuTong.setClient("1");
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(apiPlatApplyLiJiuTong));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("content", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMaskApply respApply(String respJson) throws Exception {
        //  进件返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        return RespPlatformPhoneMaskApply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }
}
